<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use app\portal\model\CategoryModel;
use app\portal\model\ShoppingModel;

use cmf\controller\AdminBaseController;
use Think\Db;

class AdminShoppController extends AdminBaseController
{


    /** 商品记录
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {

        $arr = $arr_c = [];
        $keyword = $c_id =$type =  $t=  '';
        $param  = $this->request->param();
        if(!empty($param['type']) ){//吃用分类
            $t = $param['type'] ;
            $typ = $param['type'] ==1 ? [1,3,6,5,7,8,15,16]:[2,4,9,10,11,12,13,14];
            $arr['s.c_id'] = ['in',$typ];
        }

        //关键字搜索
        if(!empty($param['keyword'])){
            $keyword = $param['keyword'];
            $arr = ['s.name' =>  "$keyword"];
        }
        //时间
        if(!empty($param['c_id'])){  $arr['c_id'] = $c_id = $param['c_id']; }
        $start_time  = !empty($param['start_time']) ? $param['start_time'] : date('Y-m-').'1';
        $end_time  = $end_time_t = !empty($param['end_time']) ? $param['end_time'] : '';
        $end_time_t  = !empty($end_time_t) ? $param['end_time'] : date('Y-m-d');
        $arr_s = $arr_x = $arr;

        $t_start_time = $this->time_xxx($start_time);
        $t_end_time = $this->time_xxx($end_time_t);

        $arr_s['s.date'] = ['between',[$t_start_time.' 00:00',$t_end_time.' 23:59']];
        $arr_x['s.date'] = ['between',[$start_time.' 00:00',$end_time_t.' 23:59']];

        if($start_time && $end_time ){
            $arr['s.date'] = ['between',[$start_time.' 00:00',$end_time.' 23:59']];
        }elseif ($start_time && !$end_time ){
            $arr['s.date'] = ['>=',$start_time.' 00:00'];
        }elseif (!$start_time && $end_time ){
            $arr['s.date'] = ['<',$end_time.' 23:59'];
        }


        $portalCategoryModel = new CategoryModel();
        $category = $portalCategoryModel->where($arr_c)->select();

        $list = (new ShoppingModel())->shopping($arr);

        $total = (new ShoppingModel())->alias('s')->where($arr)->sum('price');
        /* 本月100，上月40
        (100-40)/40*/
        //查询上一月对应日期的消费
        $x_total = (new ShoppingModel())->alias('s')->where($arr_x)->sum('price');
           $s_price = (new ShoppingModel())->alias('s')->where($arr_s)->sum('price');

        $baifei = 0;
        if(!empty($x_total)&&!empty($s_price)) {
            $baifei = ($x_total - $s_price) / $s_price;
        }

      // dump('上个月：'.$s_price);   dump('这个月：'.$x_total);
        $num = str_replace('-','',$baifei);
        $att = ['s_price'=>$s_price,'type'=>'同比上月上升','money'=>round($num,2).'%'];
        if($baifei<0){
            $num = str_replace('-','',$baifei);
            $att = ['s_price'=>$s_price,'type'=>'同比上月下降','money'=>round($num,2).'%'];
        }


        $this->assign('total', $total);//价格总计

        $this->assign('type_a', [1=>'吃',2=>'用']);
        $this->assign('type',$type);
        $this->assign('start_time', $start_time);
        $this->assign('end_time', $end_time);
        $this->assign('keyword', $keyword);//搜索条件
        $this->assign('c_id', $c_id);//搜索条件
        $this->assign('data',  $list->toArray()['data'] );
        $list->appends($param);//分页保留参数
        $this->assign('page', $list->render());//分页

        $this->assign('category', $category);

        $this->assign('t', $t);
        $this->assign('day', date('m'));
        $this->assign('tt', $att);

        return $this->fetch();
    }
    public function time_xxx($_time){
        $arr_ = explode('-',$_time);

        $i=0;
        foreach ($arr_ as &$v){
            $i++;
            if($i!=2){ continue; }
            if((int)$v==1){
                $arr_[1] = (int)$arr_[1]-1;
                $v = 12;
            }else{
                $v = (int)$v-1;
            }
            if(strlen($v)==1){ $v = '0'.$v;}

        }

        return implode('-',$arr_);
    }
    //分类查询
    public function c_type()
    {

        $arr = $arr_c = [];
        $keyword = $c_id =$type =  $t=  '';
        $param  = $this->request->param();


        //时间
        $start_time  = isset($param['start_time']) ? $param['start_time'] : date('Y-m-').'1';
        $end_time  = isset($param['end_time']) ? $param['end_time'] : '';
        if($start_time && $end_time ){
            $arr['s.date'] = ['between',[$start_time.' 00:00',$end_time.' 23:59']];

        }elseif ($start_time && !$end_time ){
            $arr['s.date'] = ['>=',$start_time.' 00:00'];

        }elseif (!$start_time && $end_time ){
            $arr['s.date'] = ['<',$end_time.' 23:59'];
        }

        $total = (new ShoppingModel())->alias('s')->where($arr)->sum('price');

        $portalCategoryModel = new CategoryModel();

        $category = $portalCategoryModel->where([])->order('id','asc')->select();
        foreach ($category as &$val){
            $arr['c_id'] = $val['id'];
            $val['total'] = (new ShoppingModel())->alias('s')->where($arr)->sum('price');
        }
        $this->assign('data', $category);



        $this->assign('total', $total);//价格总计
        $this->assign('start_time', $start_time);
        $this->assign('end_time', $end_time);
        return $this->fetch();
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add_q()
    {
        $Category = new ShoppingModel();
        if($this->request->isPost()) {

            $where = [];
            $param = $this->request->param();
            if (empty($param['c_id'])) { $this->error('请先选择分类', ''); }
            if (empty($param['name'])) { $this->error('商品名不能为空', ''); }
            if (empty($param['price'])) { $this->error('价格不能为空', ''); }
            if (empty($param['num'])) { $this->error('数量不能为空', ''); }
            $arr = [
                'name' => $param['name'],
                'c_id' => $param['c_id'],
                'num' => intval($param['num']),
                'price' => $param['price'],
                'remark' => $param['remark'],
                'date' => $param['date'],
            ];

            if (!empty($param['id'])) {

                $where['id'] = $param['id'];
                $Category->where($where)->update($arr);

            } else {
                if(empty($arr['date'])){   $arr['date'] = date('Y-m-d '); }
                $arr['create_time'] = date('Y-m-d H:i:s');
                $Category->insert($arr);
            }

            $this->success('操作成功', url('AdminShopp/index'));

        }else{
            $id = $this->request->param('id');
            $data = $Category ->where(['id'=>$id])->find();
            $this->assign('data', $data);//搜索条件

            $category = (new CategoryModel())->select();
            $this->assign('category', $category);
            return $this->fetch('add');
        }

    }
    /**
     * 分类列表
     */
    public function category()
    {
        $arr = $arr_c = [];
        $keyword ='';
        $param  = $this->request->param();
        if(!empty($param['keyword'])){ $arr['name'] = $keyword = $param['keyword']; }
        if(!empty($param['c_id'])){ $arr_c['id'] = $param['c_id']; }
        $portalCategoryModel = new CategoryModel();
        $list = $portalCategoryModel->category_list($arr_c);
        $this->assign('keyword', $keyword);//搜索条件

        $list->appends($param);//分页保留参数
        $this->assign('page', $list->render());//分页

        $this->assign('data',  $list->toArray()['data'] );


        return $this->fetch();
    }
    public function add_c()
    {
        $Category = new CategoryModel();
        if($this->request->isPost()) {

            $arr = $where = [];
            $param = $this->request->param();

            if (empty($param['name'])) {
                $this->error('分类名不能为空', '');
            }
            $arr = [
                'name' => $param['name'],
                'remark' => $param['remark'],
            ];

            if (!empty($param['id'])) {
                $wh = [ 'name' => $param['name']];
                $wh['id'] = ['NEQ',$param['id']] ;
                $refindus = $Category->where($wh)->find();
                if($refindus){  $this->error('分类名已存在', ''); }
                $where['id'] = $param['id'];

                $res = $Category->where($where)->update($arr);

            } else {
                $refindus = $Category->where([ 'name' => $param['name']])->find();
                if($refindus){  $this->error('分类名已存在', ''); }
                $arr['create_time'] = date('Y-m-d H:i:s');
                $res = $Category->insert($arr);
            }

              $this->success('操作成功', url('AdminShopp/category'));

        }else{
            $id = $this->request->param('id');
            $data = $Category ->where(['id'=>$id])->find();
            $this->assign('data', $data);//搜索条件
            return $this->fetch();
        }

    }
   //分类删除
    public function delete_c($id){
       if( CategoryModel::destroy($id)){
           $this->success('删除成功');
       }
       $this->error('删除失败');
    }


}